<?php
namespace addons\service\library;

use fast\Random;

class Common
{
    /**
     * 计算距离
     * @param $lng1
     * @param $lat1
     * @param $lng2
     * @param $lat2
     * @return string
     */
    public static function distance($lng1,$lat1,$lng2,$lat2)
    {
        $radLat1 = deg2rad((float)$lat1);
        $radLat2 = deg2rad((float)$lat2);
        $radLng1 = deg2rad((float)$lng1);
        $radLng2 = deg2rad((float)$lng2);
        $a = $radLat1-$radLat2;
        $b = $radLng1-$radLng2;
        $s = 2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;
        return sprintf("%.2f",round($s,2)/1000);
    }

    /**
     * 高德地图获取城市地址信息
     * @param $params
     * @return mixed
     */
    public static function getAreaList($params)
    {
        $config = \app\api\model\service\ProjectConfigure::getProjectConfig();
        $url = "https://restapi.amap.com/v3/place/text";
        $requestUrl = $url . "?key=" . $config['gaodekey'] . "&keywords=" . $params['name']. "&city=" . $params['city'].'&citylimit=true&children=1';
        $curl = curl_init($requestUrl);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true);;
    }


    /**
     * 创建二维码
     * @param $str
     * @return string
     */
    public static function createQrcode($str)
    {
        require_once ROOT_PATH.'addons/service/library/qrcode/phpqrcode.php';
        $path ='/public/uploads/qrcode/'.date("Y-m-d").'/';
        if (!is_dir(ROOT_PATH.$path))
        {
            mkdir(ROOT_PATH.$path,0777,true);
        }
        $file = "/uploads/qrcode/".date("Y-m-d").'/'.time().Random::alnum().".png";
        $fileName = $_SERVER['DOCUMENT_ROOT'].$file;
        $img = ImageCreate(900,900);
        $color = ImageColorAllocate($img,255,255,255);
        ImageFill($img,0,0,$color);
        imagepng($img,$fileName);
        $link = $str;
        $errorCorrectionLevel = "L";
        $matrixPointSize = "4";
        \QRcode::png($link, $fileName, $errorCorrectionLevel, $matrixPointSize);
        return $file;
    }

    public static function getDistrict($areaData)
    {
        // 按照首字母拼音排序
        $district = array();
        foreach( $areaData as $name )
        {
            $snameFirstChar = $name['first'];
            $district[$snameFirstChar][] =$name;
        }
        ksort($district);//排序
        return $district;
    }

}
